<?php


namespace app\ymsh\controller\java;


use app\model\AgentExtend;
use think\Db;
use think\Exception;
use think\facade\Log;

class Agent extends BaseController
{
    /**
     * 应用绑定代理
     */
    public function bindAgent()
    {
        $params = request()->only(['agent_id', 'app_id', 'merchant_id', 'merchant_name', 'app_name']);

        $msg = dmjValidate([
            'agent_id' => 'require|number',
            'app_id' => 'require|number',
            'merchant_id' => 'require|number',
            'merchant_name' => 'require',
            'app_name' => 'require',
        ], [], $params);

        if ($msg) {
            return fail($msg);
        }

        try {
            \think\facade\Db::startTrans();

            $extend = AgentExtend::findOrCreate($params);

            /**
             * @var AgentExtend $extend
             */
            $extend->agent->merchant_id = $extend->merchant_id;
            $extend->agent->app_id = $extend->app_id;
            $extend->agent->save();

            \think\facade\Db::commit();

            return success('操作成功',[
                'name' => $extend->agent->company_name,
                'username' => $extend->agent->username,
            ]);
        } catch (Exception $exception) {
            Log::error($exception->getMessage());
            \think\facade\Db::rollback();
            return fail('绑定错误或已绑定');
        }
    }



}